<template>
    <dl-card style="max-width: 99%">
      <el-form :inline="true" :model="page" class="demo-form-inline">
      <el-form-item label="物料主题">
        <el-input v-model="page.materialtheme" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="物料编号">
        <el-input v-model="page.materialCode" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="产品名称">
        <el-input v-model="page.productName" placeholder="请输入" clearable />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="getMateial">查找</el-button>
      </el-form-item>
    </el-form>
    </dl-card>
    <dl-card style="max-width: 99%">
      
    <el-button type="success" @click="addmaterial">新增物料</el-button>
    <el-button type="danger" @click="deletemateil">删除</el-button> 
        <el-button type="primary" @click="updateMaterial">修改</el-button>
        <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" border highlight-current-row
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
    <!-- 主表字段 -->
    <el-table-column  type="index" label="序号" align="center"/>
    <el-table-column prop="materialtheme" label="物料清单主题" align="center" />
    <el-table-column prop="materialCode" label="物料清单编号" align="center" />
    <el-table-column prop="list" label="主辅清单" align="center" />
    
    <!-- 显示第一条子表数据 -->
    <el-table-column prop="materialInformationList" label="产品名称" align="center">
      <template v-slot="scope">
        {{ scope.row.materialInformationList[0]?.productName || '无' }}
      </template>
    </el-table-column>
    
    <el-table-column prop="addDateTime" label="制单日期" align="center">
      <template v-slot="scope">
                    <el-text>{{ moment(scope.row.addDateTime).format("YYYY年MM月DD日") }}</el-text>
                </template>
    </el-table-column>
    
    <!-- 操作列 -->
    <el-table-column fixed="right" label="操作" align="center" width="180">
      <template v-slot="scope">
        <el-button link type="primary" size="small">详情</el-button>
      </template>
    
    </el-table-column>
  </el-table>
    </dl-card>
    <!-- 物料添加框 -->
    <el-dialog v-model="dialogFormVisible" title="物料新增" width="1000">
        <el-form ref="ruleFormRef" style="max-width: 1000px" :model="ruleForm" :rules="rules" label-width="auto">
    <el-form-item label="物料清单主题" prop="materialtheme">
      <el-input v-model="ruleForm.materialtheme" />
    </el-form-item>
            <el-form-item label="物料清单编号" prop="materialCode">
                <el-input v-model="ruleForm.materialCode" disabled />
    </el-form-item>
    <el-form-item label="制单人员" prop="creator">
                <el-input v-model="ruleForm.creator" disabled />
    </el-form-item>
    <el-form-item label="主辅料">
      <el-input v-model="ruleForm.list" />
    </el-form-item>
      <div style="display: flex; align-items: center; margin-bottom: 8px;">
            <span style="font-weight: bold;">配件信息</span>
            <el-button size="small" style="margin-left: 8px;" @click="addHealthRow">新建行</el-button>
          </div>
          <el-table :data="ruleForm.information" border style="width: 100%; margin-top: 10px;">
    <el-table-column prop="productName" label="产品名称" width="150">
      <template #default="scope">
        <template v-if="scope.row.editing">
                            <el-input v-model="scope.row.productName" size="small" maxlength="5" />
        </template>
        <template v-else>
          {{ scope.row.productName }}
        </template>
      </template>
    </el-table-column>
    <el-table-column prop="productCode" label="产品编号" width="100">
      <template #default="scope">
        <template v-if="scope.row.editing">
          <el-input v-model="scope.row.productCode" size="small" maxlength="30" />
        </template>
        <template v-else>
          {{ scope.row.productCode }}
        </template>
      </template>
    </el-table-column>
    <el-table-column prop="model" label="规格型号" width="100">
      <template #default="scope">
        <template v-if="scope.row.editing">
          <el-input v-model="scope.row.model" size="small" maxlength="30" />
        </template>
        <template v-else>
          {{ scope.row.model }}
        </template>
      </template>
    </el-table-column>
    <el-table-column prop="unit" label="单位" width="100">
      <template #default="scope">
        <template v-if="scope.row.editing">
          <el-input v-model="scope.row.unit" size="small" maxlength="30" />
        </template>
        <template v-else>
          {{ scope.row.unit }}
        </template>
      </template>
    </el-table-column>
    <el-table-column prop="proportion" label="产品比例" width="100">
      <template #default="scope">
        <template v-if="scope.row.editing">
          <el-input v-model="scope.row.proportion" size="small" maxlength="30" />
        </template>
        <template v-else>
          {{ scope.row.proportion }}
        </template>
      </template>
    </el-table-column>
    <el-table-column prop="quantity" label="数量" width="100">
      <template #default="scope">
        <template v-if="scope.row.editing">
          <el-input v-model="scope.row.quantity" size="small" maxlength="30" />
        </template>
        <template v-else>
          {{ scope.row.quantity }}
        </template>
      </template>
    </el-table-column>
    <el-table-column prop="productRole" label="产品角色" width="100">
      <template #default="scope">
        <template v-if="scope.row.editing">
                            <el-select v-model="scope.row.productRole" clearable>
        <el-option label="自制" value="自制" />
        <el-option label="外委" value="外委" />
        <el-option label="外购" value="外购" />
      </el-select>
        </template>
        <template v-else>
          {{ scope.row.productRole }}
        </template>
      </template>
    </el-table-column>
    <el-table-column prop="attritioRate" label="耗损率" width="100">
      <template #default="scope">
        <template v-if="scope.row.editing">
          <el-input v-model="scope.row.attritioRate" size="small" maxlength="30" />
        </template>
        <template v-else>
          {{ scope.row.attritioRate }}
        </template>
      </template>
    </el-table-column>
    <el-table-column prop="picking" label="领料方式" width="100">
      <template #default="scope">
        <template v-if="scope.row.editing">
                            <el-select v-model="scope.row.picking" clearable>
        <el-option label="正常领料" value="正常领料" />
        <el-option label="倒冲领料" value="倒冲领料" />
      </el-select>
         
        </template>
        <template v-else>
          {{ scope.row.picking }}
        </template>
      </template>
    </el-table-column>
    <el-table-column prop="notes" label="备注" width="100">
      <template #default="scope">
        <template v-if="scope.row.editing">
          <el-input v-model="scope.row.notes" size="small" maxlength="30" />
        </template>
        <template v-else>
          {{ scope.row.notes }}
        </template>
      </template>
    </el-table-column>
    <!-- 其他列... -->
    <el-table-column label="操作" width="100">
      <template #default="scope">
        <template v-if="scope.row.editing">
          <el-link type="primary" @click="saveRow(scope.row)">保存</el-link>
          <el-link type="info" style="margin-left: 8px;" @click="cancelEdit(scope.row)">取消</el-link>
        </template>
        <template v-else>
          <el-link type="primary" @click="editRow(scope.row)">编辑</el-link>
          <el-link type="danger" style="margin-left: 8px;" @click="deleteRow(scope.row)">删除</el-link>
        </template>
      </template>
    </el-table-column>
  </el-table>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        保存
      </el-button>
                <el-button @click="dialogFormVisible = false;">关闭</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
  <el-dialog v-model="dialoginformation" title="配件信息" width="500">

  </el-dialog>
    </template>
    
    <script lang="ts" setup>
    import axios from 'axios';
    import type { TableInstance } from 'element-plus'
    import { read } from '../../stores/host';
    import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
    import { onMounted, reactive, ref, watch } from 'vue';
    import moment from 'moment';
    
    // 类型定义
    interface MaterialInformation {
      id: number;
      keyId: number;
      productName: string;
      productCode: string;
      model: string;
      unit: string;
      proportion: string;
      quantity: string;
      productRole: string;
      attritioRate: string;
      picking: string;
      notes: string;
      editing: boolean;
      isNew: boolean;
    }
    
    interface MainMaterial {
      id: number;
      materialtheme: string;
      materialCode: string;
      list: string;
      creator: number;
      addDateTime: Date;
      materialInformationList: MaterialInformation[];
    }
    
    interface RuleForm {
      id: number;
      materialtheme: string;
      materialCode: string;
      list: string;
      creator: number;
      addDateTime?: string;  // 添加这个字段
      information: MaterialInformation[];
    }
    
    // 组件逻辑
    const multipleTableRef = ref<TableInstance>();
    const multipleSelection = ref<MainMaterial[]>([]);
    const dialoginformation = ref(false);
    const dialogFormVisible = ref(false);
    const tableData = ref<MainMaterial[]>([]);
    const ruleFormRef = ref<FormInstance>();
    
    const page = reactive({
      totalCount: 0,
      totalPage: 0,
      PageSize: 15,
      PageIndex: 1,
      materialtheme: "",
      materialCode: "",
      productName: ""
    });
    
    const rules = reactive<FormRules>({
      materialtheme: [
        { required: true, message: '物料清单主题不能为空', trigger: 'blur' },
      ],
      addUserName: [
        { required: true, message: '产品名称不能为空', trigger: 'blur' },
      ]
    });
    
    // 生成物料编号
    const generateDateBasedNumber = (incrementLength: number = 4) => {
      const now = new Date();
      const datePart = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
      const storageKey = `dateNumCounter_${datePart}`;
      let currentCount = localStorage.getItem(storageKey) || '0';
      const numericCount = parseInt(currentCount, 10) + 1;
      currentCount = numericCount.toString();
      localStorage.setItem(storageKey, currentCount);
      return datePart + currentCount.padStart(incrementLength, '0');
    };
    
    const ruleForm = reactive<RuleForm>({
      id: 0,
      materialtheme: "",
      materialCode: generateDateBasedNumber(),
      list: "",
      creator: 1,
      information: [createEmptySubItem(false)],
    });
    
    // 辅助函数：创建空子表项
    function createEmptySubItem(isNew: boolean): MaterialInformation {
      return {
        id: 0,
        keyId: 0,
        productName: "",
        productCode: "",
        model: "",
        unit: "",
        proportion: '',
        quantity: '',
        productRole: "",
        attritioRate: '',
        picking: "",
        notes: "",
        editing: isNew,
        isNew
    }
    }
    
    // 表格选择处理
    const handleSelectionChange = (val: MainMaterial[]) => {
    console.log('当前选中行:', val)
    multipleSelection.value = val
}
    
    // 获取物料数据
    const getMateial = async () => {
      try {
        const res = await read.get("readproduce/api/Maxage/GetMaterial", {
          params: {
            Materialtheme: page.materialtheme,
            MaterialCode: page.materialCode,
            productName: page.productName,
            PageSize: page.PageSize,
            PageIndex: page.PageIndex
          }
        })
        
        tableData.value = res.data.data
        page.totalCount = res.data.totalCount
        page.totalPage = res.data.totalPage
      } catch (error) {
        console.error('获取物料数据失败:', error)
        ElMessage.error('获取数据失败')
      }
}
    
    // 新增行
    const addHealthRow = () => {
    ruleForm.information.push(createEmptySubItem(true))
}
    
    // 行操作
    const editRow = (row: MaterialInformation) => {
    row.editing = true
}
    
    const saveRow = (row: MaterialInformation) => {
      row.editing = false;
      row.isNew = false;
    };
    
    const cancelEdit = (row: MaterialInformation) => {
      if (row.isNew) {
        const index = ruleForm.information.findIndex(item => item.id === row.id);
        if (index !== -1) {
          ruleForm.information.splice(index, 1);
        }
      } else {
        row.editing = false;
      }
    };
    
    const deleteRow = (row: MaterialInformation) => {
      const index = ruleForm.information.indexOf(row);
      if (index !== -1) {
        ruleForm.information.splice(index, 1);
      }
    };
    
    // 新增物料
    const addmaterial = () => {
      ruleForm.id = 0;
      ruleForm.materialtheme = "";
      ruleForm.materialCode = generateDateBasedNumber();
      ruleForm.list = "";
      ruleForm.creator = 1;
     
      ruleForm.information = [createEmptySubItem(true)];
      dialogFormVisible.value = true;
    };
    
    // 反填数据
    const updateMaterial = async () => {
      if (multipleSelection.value.length !== 1) {
        ElMessage.warning("请选择一行数据");
        return;
      }
    
      const selectedRow = multipleSelection.value[0];
      console.log('选中行数据:', selectedRow);
    
      // 重置表单
      ruleFormRef.value?.resetFields();
    
      // 主表数据
      ruleForm.id = selectedRow.id;
      ruleForm.materialtheme = selectedRow.materialtheme || "";
      ruleForm.materialCode = selectedRow.materialCode || "";
      ruleForm.list = selectedRow.list || "";
      ruleForm.creator = selectedRow.creator || 1;
      ruleForm.addDateTime = moment(selectedRow.addDateTime).format("YYYY-MM-DD HH:mm:ss"); // 反填日期
    
      // 子表数据
      ruleForm.information = (selectedRow.materialInformationList || []).map(item => ({
        ...item,
         id: item.id || 0,
        
        editing: false,
        isNew: false
      }));
    
      // 确保至少有一行
      if (ruleForm.information.length === 0) {
        addHealthRow();
      }
    
      dialogFormVisible.value = true;
    };
    
    // 提交表单
    const submitForm = async (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      
      try {
        await formEl.validate();
        
        // 过滤空行
        const validInformation = ruleForm.information.filter(item => 
          item.productName || item.productCode
        );
        
        const payload = {
          ...ruleForm,
          information: validInformation
        };
        
        const url = ruleForm.id 
          ? "writeproduce/api/Mateial/UpdateMaterial" 
          : "writeproduce/api/Mateial/AddMaterial";
        
        const method = ruleForm.id ? 'put' : 'post';
        
        const res = await read[method](url, payload);
        
        if (res.data.code === 200) {
          ElMessage.success(res.data.message);
          dialogFormVisible.value = false;
          getMateial();
        } else {
          ElMessage.error(res.data.message);
        }
      } catch (error) {
        console.error('表单提交错误:', error);
        if (error !== 'cancel') {
          ElMessage.error('提交失败');
        }
      }
    };
    
    // 删除物料
    const deletemateil = async () => {
      if (multipleSelection.value.length === 0) {
        ElMessage.warning('请先选择要删除的数据');
        return;
      }
    
      const row = multipleSelection.value[0];
      const id = Number(row.id);
      
      if (!id) {
        ElMessage.error('选中的数据无效，缺少ID');
        return;
      }
    
      try {
        await ElMessageBox.confirm(
          `确定要删除【${row.materialtheme}】吗？`,
          '删除确认',
          { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
        );
    
        const response = await read.post(
          `writeproduce/api/Mateial/DeleteMaterial?id=${id}`
        );
        
        if (response.data.code === 200) {
          ElMessage.success('删除成功');
          getMateial();
          multipleTableRef.value?.clearSelection();
        } else {
          ElMessage.error(response.data.message || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除错误:', error);
          ElMessage.error('删除失败');
        }
      }
    };
    
    // 生命周期
    onMounted(() => {
      getMateial();
    });
    
    watch(page, () => {
      getMateial();
    });
    </script>
    